<?php
namespace App\Service\ApiQd;

use Illuminate\Support\Facades\DB;

class MaterialService extends BaseService
{

    /**
     * 可用列表
     * @param array $pages【start，limit】
     * @return array
     */
    public function getList($pages, $keyword = '')
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbwbConn($this->dbDistributorMaterial)->where('del', 0);
        if (!empty($keyword)) {
            $db = $db->where('title', 'like', '%'.$keyword.'%');
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => 0);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $imgs = $this->dbwbConn($this->dbDistributorMaterialImg)->where('del', 0)->where('dmid', $v['id'])->get();

            $img_list = [];
            foreach ($imgs as $img){
                $img = (array)$img;
                $img_list[] = env('DOMAIN') . '/' . $img['link'];
            }
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'detail' =>$v['detail'],
                'imgs' => $img_list,
                'addtime' => $v['addtime'],
                'logo' => env('DOMAIN') . '/' . 'images/logo.jpg'
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 获取
     * @param int $uid
     */
    public function getOne($id)
    {
        $material = (array)$this->dbwbConn($this->dbDistributorMaterial)
            ->where('id', $id)
            ->where('del', 0)
            ->first();
        if (empty($material)) {
            return array('code' => -2, 'msg' => '没有数据');
        }
        $material_imgs = $this->dbwbConn($this->dbDistributorMaterialImg)
            ->where('dmid', $material['id'])
            ->where('del', 0)
            ->get();
        foreach ($material_imgs as $material_img){
            $material_img = (array)$material_img;
            $material['imgs'][] = env('DOMAIN') . '/' . $material_img['link'];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $material);
    }
}